from typing import List
from fastapi import APIRouter, Body
from app.schemas.battery import BatteryCreate, BatteryOut
from app.crud import battery as crud_battery
from tortoise.exceptions import DoesNotExist
from app.utils.Result import Result

router = APIRouter()

# 创建电池
@router.post(
    "/",
    response_model=Result[BatteryOut],
    summary="创建电池",
    description="创建一个新的电池记录。"
)
async def create_battery(battery: BatteryCreate):
    battery_obj = await crud_battery.create_battery(battery.dict())
    return Result.ok(data=battery_obj)

# 根据ID查询电池
@router.get(
    "/{battery_id}",
    response_model=Result[BatteryOut],
    summary="根据电池ID获取电池信息",
    description="根据电池ID查询电池的详细信息。"
)
async def get_battery(battery_id: int):
    try:
        battery_obj = await crud_battery.get_battery_by_id(battery_id)
        return Result.ok(data=battery_obj)
    except DoesNotExist:
        return Result.error(code=404, msg="电池不存在")

# 查询所有电池
@router.get(
    "/",
    response_model=Result[list[BatteryOut]],
    summary="获取所有电池列表",
    description="返回数据库中所有电池的信息列表。"
)
async def list_all_batteries():
    batteries = await crud_battery.list_batteries()
    return Result.ok(data=batteries)

@router.delete(
    "/batch",
    response_model=Result[str],
    summary="批量删除电池",
    description="根据电池ID列表批量删除对应的电池记录。"
)
async def delete_batteries(battery_ids: List[int] = Body(..., embed=True, description="要删除的电池ID列表")):
    deleted = await crud_battery.delete_batteries(battery_ids)
    if deleted == 0:
        return Result.error(code=404, msg="删除失败，没有匹配的电池")
    return Result.ok(msg=f"删除成功，共删除 {deleted} 条记录")

# 根据ID删除电池
@router.delete(
    "/{battery_id}",
    response_model=Result[str],
    summary="根据电池ID删除电池",
    description="根据电池ID删除对应的电池记录。"
)
async def delete_battery(battery_id: int):
    deleted = await crud_battery.delete_battery(battery_id)
    if deleted == 0:
        return Result.error(code=404, msg="删除失败，电池不存在")
    return Result.ok(msg="删除成功")

